﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Linq;
using Config.Core;

namespace Config.Console
{
    public class ConsoleDriver
    {
        /// <summary>
        /// Entry point to the application.
        /// </summary>
        /// <param name="args">The comand line arguments.</param>
        public static void Main(string[] args)
        {
            try
            {
                if (args.Length == 0)
                {
                    Usage();
                    return;
                }

                var options = CommandLineOptions.Parse(args);
                if (string.IsNullOrEmpty(options.InFile))
                    throw new Exception("No input file was specified.");

                if (!string.IsNullOrEmpty(options.BaseDirectory))
                    Environment.CurrentDirectory = options.BaseDirectory;
               
                XDocument doc = XDocument.Load(options.InFile);

                XmlParser parser = new XmlParser { BaseDirectory = options.BaseDirectory };
                foreach (var key in options.Properties.Keys)
                    parser.Props.Add("cmdline." + key, options.Properties[key]);

                parser.Parse(doc);

                if (string.IsNullOrEmpty(options.OutFile))
                    doc.Save(options.InFile);
                else
                    doc.Save(options.OutFile);
            }

            catch (Exception ex)
            {
                System.Console.Error.WriteLine("ConfigManager.Net error: " + ex.Message);
                Usage();
            }
        }

        /// <summary>
        /// Prints the usage for the application.
        /// </summary>
        public static void Usage()
        {
            try
            {
                var exeDir = AppDomain.CurrentDomain.BaseDirectory;
                using (var reader = new StreamReader(exeDir + @"\usage.txt"))
                    System.Console.WriteLine(reader.ReadToEnd());
            }
            catch (Exception)
            {
                System.Console.Error.WriteLine("Could not find\read the usage file.");
            }
        }
    }
}
